﻿create or replace function posterminalSave(
	out xml, inout xml
	)
as
$$
	declare
		-- alias is name for stored procedure parameters
		executeStatusData 	alias for $1;
		posterminalData		alias for $2;
		
		vIdPosterminal 		bigint := null; -- posterminal id in database
		vSerialNumber		text := null; -- posterminal serial number
		vInventoryNumber	text := null; -- posterminal inventory number
		vIdModel			bigint := null;
		vIdCurPoslocation	bigint := null;
		vIdConnectionType	integer := null;
		
		
		vIdNode				varchar(100) := '/posterminal/@id';
		vSerialNode			varchar(100) := '/posterminal/serialnumber';
		vInventoryNode		varchar(100) := '/posterminal/inventorynumber';
		
		
	begin
		vIdPosterminal := cast(extract_value(vIdNode, posterminalData) as bigint);
		vSerialNumber := extract_value(vSerialNode, posterminalData);
		vInventoryNumber := extract_value(vInventoryNode, posterminalData);
		
		if (vIdPosterminal = null or vIdPosterminal = noId()) then begin
			insert into PosTerminal(
					serialNumber, inventoryNumber, idModel, idCurrentPosLocation, idConnectionType)
				values(
					vSerialNumber, vInventoryNumber, vIdModel, vIdCurPoslocation, vIdConnectionType)
				returning idPosTerminal into vIdPosterminal;
				posterminalData := posterminal2Xml(vIdPosterminal, vSerialNumber, vInventoryNumber, vIdModel, vIdCurPoslocation, vIdConnectionType);
				executeStatusData := statusCall(successcode(), 'Inserted');
			return;
			end;
		else begin
			update PosTerminal poal
				set 
					serialNumber 			= vSerialNumber, 
					inventoryNumber 		= vInventoryNumber,
					idModel					= vIdModel,
					idCurrentPosLocation 	= vIdCurPoslocation,
					idConnectionType		= vIdConnectionType
				where
					poal.idPosTerminal			= vIdPosterminal;
			executeStatusData := statusCall(successcode(), 'Updated');
			end;
		end if;
	end;
$$ language plpgsql VOLATILE;
		
		